package com.jnu.student.data;

import android.content.Context;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class AchievementDataStorage {
    private static final String FILENAME = "achievement_data.txt";

    // 保存成就点数据
    public synchronized void saveAchievementData(Context context, List<Double> data) {
        try {
            FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(data);
            oos.close();
            fos.close();
            Log.d("AchievementDataStorage", "Achievement data saved successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取成就点数据
    public synchronized List<Double> loadAchievementData(Context context) {
        List<Double> data = new ArrayList<>();
        try {
            FileInputStream fis = context.openFileInput(FILENAME);
            ObjectInputStream ois = new ObjectInputStream(fis);
            data = (List<Double>) ois.readObject();
            ois.close();
            fis.close();
            Log.d("AchievementDataStorage", "Achievement data loaded successfully.");
        } catch (IOException | ClassNotFoundException e) {
            Log.d("AchievementDataStorage", "No previous achievement data found, initializing with empty data.");
            data = new ArrayList<>();
        }
        return data;
    }

    // 更新成就点数据
    public synchronized void updateAchievementData(Context context, double newAchievementPoint) {
        List<Double> data = loadAchievementData(context);
        data.add(newAchievementPoint);
        if (data.size() > 15) {
            data = new ArrayList<>(data.subList(data.size() - 15, data.size()));
        }
        saveAchievementData(context, data);
    }
}